import DingdingAPI
from DingdingAPI import zhuanpai, send_message_to_dingtalk
from 获取审批单 import get_order
from 调用ERP接口 import get_for_erp
from 审批采购单 import 审批采购单
from 审批新品采购单 import 审批新品采购单
from 获取审批单 import get_order
from 数据库 import *

def main():
    try:
        order_list = get_order()
        if not order_list:
            print('没有待办审批单')
            return
        conn, cursor = connect_db()
        taskid_list = []
        for order in order_list:
            taskid_list.append(order['task_id'])
        insert_taskid(conn, cursor, taskid_list)
        for shenpi_order in order_list:
            taskid = shenpi_order['task_id']
            instanceid = shenpi_order['instance_id']
            order_title = shenpi_order['title']
            order_id = shenpi_order['indexNo']
            url = shenpi_order['url']
            paytype = shenpi_order['payType']
            print(order_title)
            print(url)
            合计金额 = float(shenpi_order['totalAmount'])
            # 数据库查询判断是否已经处理过
            result = select_taskid(cursor, taskid)
            if result == 1:
                print('该订单已被处理过')
                continue
            erp_data = get_for_erp(order_id)
            if not erp_data:
                zhuanpai(taskid, 'ERP接口未返回数据，转交人工识别', conn, cursor)
            elif '对公' in paytype:
                zhuanpai(taskid, '对公,转人工审批', conn, cursor)
            elif '新品' in order_title:
                print('新品采购单')
                审批新品采购单(erp_data, 合计金额, taskid, instanceid, conn, cursor)
            else:
                print('采购单')
                审批采购单(erp_data, 合计金额, taskid, instanceid, conn, cursor)
        sum_count = DingdingAPI.agree_count + DingdingAPI.concat_count + DingdingAPI.zhuanpai_count
        message = f'本次运行结果：共计{sum_count}条\n同意：{DingdingAPI.agree_count}条，不同意：{DingdingAPI.concat_count}条，转派：{DingdingAPI.zhuanpai_count}条'
        print(message)
        send_message_to_dingtalk(message)
        conn.close()
    except Exception as e:
        print(e)
        send_message_to_dingtalk(e)

if __name__ == '__main__':
    main()
